//
//  MiddleViewController.m
//  JSReader
//
//  Created by xzoscar on 16/6/27.
//  Copyright © 2016年 hujs. All rights reserved.
//

//
//  MiddleViewController.m
//  JSReader
//
//  Created by xzoscar on 16/6/20.
//  Copyright © 2016年 hujs. All rights reserved.
//

#import "MiddleViewController.h"
#import "Book.h"
#import "JSFileHandler.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"

static void *kObserveOffsetContext = &kObserveOffsetContext;

@interface MiddleViewController ()<UIScrollViewDelegate> {
    NSString *_backgroundColor;
    NSString *_textColor;
    NSInteger _textFontSize;
}

@property (nonatomic, strong ) Book *book;

@end

@implementation MiddleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _textFontSize = 40;
    self.webView.scrollView.bounces = NO;
    self.navigationButtonsHidden = YES;
//    self.webView.scrollView.delegate = self;
    [self setShouldStartLoadRequestHandler:^BOOL(NSURLRequest *req, UIWebViewNavigationType type) {
        if (type == UIWebViewNavigationTypeLinkClicked) {
            return NO;
        }
        return YES;
    }];
    
    __weak typeof(self) weakSelf = self;
    [self setDidFinishLoadHandler:^(UIWebView *web) {
        NSString *str = [NSString stringWithFormat:@"document.body.style.fontSize = '%dpx'",30];
//        [web stringByEvaluatingJavaScriptFromString:str];
        
        NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%lu%%'", (unsigned long)360];
        [web stringByEvaluatingJavaScriptFromString:jsString];
        [weakSelf night:nil];
    }];
    

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContent) name:kRefreshContentsNotify object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillterminate:) name:UIApplicationWillTerminateNotification object:nil];
    
    [self addObserver:self forKeyPath:@"lastOffset" options:NSKeyValueObservingOptionNew context:kObserveOffsetContext];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!self.navigationItem.leftBarButtonItem || !self.navigationItem.rightBarButtonItem) {
        MMDrawerBarButtonItem *left = [[MMDrawerBarButtonItem alloc ]initWithTarget:self action:@selector(leftBarButtonItemAction:)];
        left.tintColor = [UIColor greenColor];
        
        MMDrawerBarButtonItem *right = [[MMDrawerBarButtonItem alloc ]initWithTarget:self action:@selector(rightBarButtonItemAction:)];
        right.tintColor = [UIColor greenColor];
        self.navigationItem.leftBarButtonItem = left;
        self.navigationItem.rightBarButtonItem = right;
    }
    [self showContent];
    
}


- (IBAction)plusA:(id)sender{
    
    _textFontSize = (_textFontSize < 140) ? _textFontSize +2 : _textFontSize;
    NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%lu%%'", (unsigned long)_textFontSize];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString];
    
}


#pragma mark -

- (void)openLeftView
{
    
    [self.mm_drawerController openDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)openRightView
{
    [self.mm_drawerController openDrawerSide:MMDrawerSideRight animated:YES completion:nil];
}
- (void)showContent {
    _book = [[JSFileHandler shared] selectedBook];
    NSString *htmlName = _book.chapterAndHTMLDict[_book.selectedChapter];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",kOneBookPath([[JSFileHandler shared] selectedBookName]), htmlName ];
//    DLog(@"加载书籍：%@", filePath);
    NSURL *url = [NSURL fileURLWithPath:filePath];
    self.url = url;
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.webView.scrollView setContentOffset:CGPointMake(0, [[[JSFileHandler shared] selectedBook].offset integerValue] )];
    });
    

}

- (IBAction)day:(id)sender{
    
    _backgroundColor = @"white";
    _textColor = @"black";
    
    NSString *jsString1 = [[NSString alloc] initWithFormat:@"document.body.style.backgroundColor = 'black'"];
  
    
    
    NSString *jsString2 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '%@'",_textColor];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString1];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString2];
    
}



- (IBAction)night:(id)sender{
    
    _backgroundColor = @"#121212";
    _textColor = @"#C5C5C5";
    
    NSString *jsString1 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].bgColor= '%@'",_backgroundColor];
  
    
    NSString *jsString2 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '%@'",_textColor];
   
    [self.webView stringByEvaluatingJavaScriptFromString:jsString1];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString2];

}

- (void)yellow{
    
    _backgroundColor = @"#F7DCE3";
    _textColor = @"#3C2617";
    
    NSString *jsString1 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].bgColor= '%@'",_backgroundColor];
 
    
    
    NSString *jsString2 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '%@'",_textColor];
  
    [self.webView stringByEvaluatingJavaScriptFromString:jsString1];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString2];
    
}

- (void)gray {
    _backgroundColor = @"#58585B";
    _textColor = @"#F9F9F9";
    
    NSString *jsString1 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].bgColor= '%@'",_backgroundColor];
    
    
    NSString *jsString2 = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '%@'",_textColor];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString1];
    [self.webView stringByEvaluatingJavaScriptFromString:jsString2];
}
#pragma mark - action
- (void)leftBarButtonItemAction:(MMDrawerBarButtonItem *)item {
     [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)rightBarButtonItemAction:(MMDrawerBarButtonItem *)item {
     [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:nil];
}

#pragma mark - observer
- (void)appWillterminate:(NSNotification *)noti {
    /*
     {name = UIApplicationWillTerminateNotification; object = <UIApplication: 0x7faa23c06bf0>}
     */
//    DLog(@"%@", noti);
    [[JSFileHandler shared] saveReadRecord:_book.offset];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (context == kObserveOffsetContext) {
//        DLog(@"%@", change);
        _book.offset = (NSNumber *)change[NSKeyValueChangeNewKey ];

    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
